package br.com.bonina.contabilidade.core;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.bonina.contabilidade.util.HibernateUtil;
//TODO VERIFICAR HIBERNATE TRANSACTION
//TODO RETIRAR OBJETO DO HIBERNATE E COLOCAR NO JETTY
public class FacadeImpl<T,K> implements Facade<T, K> {

	private Session session = HibernateUtil.getSession();
	private Transaction tran = session.getTransaction();
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public T findById(Class entity, K id) throws BusinessException {
		return (T) session.load(entity, (Serializable) id);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public T findByField(Class entity, String field, Object value) throws BusinessException {
		return (T) session.createCriteria(entity).add(Restrictions.eq(field, value)).uniqueResult();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findAllOrder(Class entity, Order order) throws BusinessException {
		return session.createCriteria(entity).addOrder(order).list();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findAllbyField(Class entity, String field, Object value, Order order) throws BusinessException {
		return session.createCriteria(entity).add(Restrictions.eq(field, value)).addOrder(order).list();
	}

	public void save(T entity) throws BusinessException {
		session.save(entity);
		tran.commit();
	}

	public void update(T entity) throws BusinessException {
		session.update(entity);
		tran.commit();
	}

	public void delete(T entity) throws BusinessException {
		session.delete(entity);
		tran.commit();
	}
}
